package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.annotation.UserParamLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter Parameter) {
       // 如果是解析UserInfo 对象且贴了标签才解析
        return Parameter.getParameterType() == UserInfo.class && Parameter.hasParameterAnnotation(UserParamLogin.class);
    }

    /**
     * 如果是true 才进这个方法
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // 转成HttpServletRequest 要拿请求头
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        // 拿到token
        String token = request.getHeader("token");
        // 获得当前登陆对象
        UserInfo userInfo = userInfoRedisService.getToken(token);
        // 返回回去
        return userInfo;
    }
}
